<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>捕鱼达人</title>
    <style media="screen">
      body{
        background: black;
        text-align: center;
      }
      #canvas{
        background: url('images/game_bg_2_hd.jpg');
      }
    </style>
    <script src="js/jquery.js" charset="utf-8"></script>
    <script src="js/common.js" charset="utf-8"></script>
    <script src="js/resources.js" charset="utf-8"></script>
    <script src="js/Sprite.js" charset="utf-8"></script>
    <script src="js/Fish.js" charset="utf-8"></script>
    <script src="js/Connon.js" charset="utf-8"></script>
    <script src="js/Bullet.js" charset="utf-8"></script>
    <script src="js/Button.js" charset="utf-8"></script>
    <script src="js/Coin.js" charset="utf-8"></script>
    <script src="js/Web.js" charset="utf-8"></script>
    <script>
      window.onload = async function(){
        let canvas = document.querySelector('#canvas'),
            context = canvas.getContext('2d'),
            W = canvas.width,H = canvas.height;
        let conAudio = document.querySelector('#connon'),
            coinAudio = document.querySelector('#coin');
        let canClick = false;  //区别mousedown，mouseup和click的事件

        //加载图片资源，这里的await一定要加
        try {
          await loadResources();
        } catch (e) {
          alert('加载资源失败，请刷新重试。');
        }

        //1.炮台
        let data_bar = __g_resources.bottom.bottom_bar;
        let bottom_bar = new Sprite({
          image:data_bar.image,
          sx:data_bar.frame.x,
          sy:data_bar.frame.y,
          w:data_bar.frame.w,
          h:data_bar.frame.h,
          x:400,
          y:566
        });
        //能量柱
        let data_energy = __g_resources.bottom.energy_column;
        let energy_column = new Sprite({
          image:data_energy.image,
          sx:data_energy.frame.x,
          sy:data_energy.frame.y,
          w:data_energy.frame.w,
          h:data_energy.frame.h,
          x:668,
          y:585   //中心坐标
        });

        //2.默认炮筒为1类型
        let connon = new Connon(1);

        //3.升级炮台的按钮
        let bottomData = __g_resources.bottom,
            oButtonMinus = new Button(bottomData.cannon_minus,
                      bottomData.cannon_minus_down),
            oButtonPlus = new Button(bottomData.cannon_plus,
                      bottomData.cannon_plus_down);
        //设置按钮的坐标位置
        oButtonMinus.x = connon.x - 50;
        oButtonMinus.y = connon.y + 10;  //(392,582)
        oButtonPlus.x = connon.x + 50;
        oButtonPlus.y = connon.y + 10;  //(492,582)

        //4.升级炮台按钮
        canvas.addEventListener('mousedown',function(ev){
          if (oButtonMinus.checkDown(ev.offsetX,ev.offsetY)) {
            //只有大于1才能降级炮筒
            if (connon.type > 1) {
              connon.setType(connon.type-1);
            }
            canClick = true;
          }
          if (oButtonPlus.checkDown(ev.offsetX,ev.offsetY)) {
            //只有小于7才能降级炮筒
            if (connon.type < 7) {
              connon.setType(connon.type+1);
            }
            canClick = true;
          }
        },false);
        canvas.addEventListener('mouseup',function(ev){
          let minus = false,plus = false;
          minus=oButtonMinus.checkUp(ev.offsetX,ev.offsetY);
          plus=oButtonPlus.checkUp(ev.offsetX,ev.offsetY);
          if (minus || plus) {
            canClick = true;
          }
        },false);

        //5.炮筒跟随鼠标移动
        canvas.addEventListener('mousemove',function(ev){
          //鼠标的坐标和炮筒坐标夹角
          let x = ev.offsetX - connon.x,
              y = ev.offsetY - connon.y;
          //设置炮台旋转角度
          connon.rotation = Math.atan2(y,x) * 180 / Math.PI + 90;
        },false);

        //每10s恢复10能量
        setInterval(function(){
          if (connon.energy<2140) {
            energy_column.w++;
            energy_column.x += 1/2;  //避免左移
            connon.energy += 10;
          }
        },1000*10);

        //6.点击发射炮弹，开完炮之后需要把能量减去
        let bullets = [],isFire = false;
        canvas.addEventListener('click',function(ev){
            //判断能量是否足够发射当前的炮弹
            if (connon.energy >= connon.type * 10 && !canClick) {
              //1.产生子弹存放在数组中
              let bullet = new Bullet(connon.type);
              bullet.x = connon.x;
              bullet.y = connon.y;
              bullet.rotation = connon.rotation;
              bullets.push(bullet);
              //2.减去能量，默认能量是2140，能量柱的长度为214px，比例是10
              connon.energy -= connon.type * 10;
              energy_column.w -= connon.type;
              energy_column.x -= connon.type/2;  //避免能量柱左移
              //3.判断炮筒是否执行动画帧
              isFire = true;
              //4.播放开炮声音
              conAudio.load();
              conAudio.play();
            }
            canClick = false;
        },false);

        //7.随机生成鱼，鱼分成左右游出的
        let fishs = [];
        setInterval(function(){
           if (Math.random() < 0.1) {
             if (Math.random() < 0.95) {
               let fish = new Fish(randomIntegerInRange(1,5));
               //左边游出
               if (Math.random() < 0.5) {
                 fish.x = -100;
                 fish.y = randomIntegerInRange(0,H);
                 fish.rotation = 90;
                 fishs.push(fish);
               } else { //右边游出
                 fish.x = W+100;
                 fish.y = randomIntegerInRange(0,H);
                 fish.rotation = -90;
                 fish.scaleY = -1;
                 fishs.push(fish);
               }
             } else {
               let fish = new Fish(randomIntegerInRange(6,7));
               //左边游出
               if (Math.random() < 0.5) {
                 fish.x = -100;
                 fish.y = randomIntegerInRange(0,H);
                 fish.rotation = 90;
                 fishs.push(fish);
               } else { //右边游出
                 fish.x = W+100;
                 fish.y = randomIntegerInRange(0,H);
                 fish.rotation = -90;
                 fish.scaleY = -1;
                 fishs.push(fish);
               }
             }
           }
         },50);

        //8.动画
        let coins = [],webs = [];
        requestAnimationFrame(next);
        function next(){
          //1.清空画布
          context.clearRect(0,0,canvas.width,canvas.height);

          //2.移动
          //清除canvas外的子弹
          bullets = bullets.filter(bullet=>!bullet.isOutOfCanvas(W,H));
          bullets.forEach(bullet=>bullet.move());
          //清除canvas外的鱼
          fishs = fishs.filter(fish=>!fish.isOutOfCanvas(W,H));
          fishs.forEach(fish=>{
            //如果鱼死了，那么就不在移动了，原地挣扎
            if(fish.lifeValue >= 0){
              fish.move();
            }else {
              if(fish.isFishDie == false){
                fish.frame = fish.max_frame/2; //设置起始帧
                fish.isFishDie = true;
              }
            }
          });
          fishs.forEach((fish,index)=>{
            //鱼已经死了而且做完了挣扎，那么渔网和鱼消失，产生金币
            if (fish.nextFrame() && fish.isFishDie && fish.lifeValue < 0) {
              fishs.splice(index,1);
              //也删除网
              webs.forEach((web,index)=>{
                if (web.keep && (web.x == fish.x) && (web.y == fish.y)) {
                  webs.splice(index,1);
                  //产生金币和银币
                  let type = fish.type >= 6 ? 2 : 1;
                  let coin = new Coin(type);
                  coin.x = web.x;
                  coin.y = web.y;
                  coins.push(coin);
                }
              });
            }
          });
          //碰撞检测
          bullets.forEach((bullet,b_index)=>{
            fishs.forEach((fish,f_index)=>{
              if(fish.collisionTest(bullet)){
                //消失
                bullets.splice(b_index,1);
                //鱼的生命值需要减少
                fish.lifeValue -= bullet.type;
                //fishs.splice(f_index,1);

                //产生网
                let web = new Web(bullet.type);
                web.x = fish.x;
                web.y = fish.y;
                //如果鱼已经死了，那么渔网留下网着鱼在那里挣扎
                //第二个条件，避免一条死鱼，重复打的时候，渔网无法消失
                if(fish.lifeValue < 0 && !fish.isFishDie){
                  web.keep = true;
                }
                webs.push(web);
              }
            });
          });
          //金币的动画帧，金币消失时，金币的数量需要增加
          coins.forEach((coin,index)=>{
            if(coin.nextFrame()){
              coins.splice(index,1);
              //金币和能量的关系
              coinAudio.play();
            }
          });
          //炮筒的动画帧是否需要停止
          if(isFire){
            if (connon.nextFrame()) {
              isFire = false;
            }
          }
          //渔网是否需要消失
          webs.forEach((web,index)=>{
            if (!web.keep) {
              webs.splice(index,1);
            }
          });

          //3.绘制
          fishs.forEach(fish=>fish.draw(context));
          bottom_bar.draw(context);
          energy_column.draw(context);
          connon.draw(context);
          bullets.forEach(bullet=>bullet.draw(context));
          oButtonMinus.draw(context);
          oButtonPlus.draw(context);
          coins.forEach(coin=>coin.draw(context));
          webs.forEach(web=>web.draw(context));

          requestAnimationFrame(next);
        }
      };
    </script>
  </head>
  <body>
    <canvas id="canvas" width="800" height="600"></canvas>
    <audio id="connon" controls="controls" style="display:none;">
      <source src="./sound/cannon.mp3" type="audio/ogg">
      <source src="./sound/cannon.mp3" type="audio/mpeg">
    </audio>
    <audio id="coin" controls="controls" style="display:none;">
      <source src="./sound/coin.wav" type="audio/ogg">
      <source src="./sound/coin.wav" type="audio/mpeg">
    </audio>
  </body>
</html>
